package com.gui.design.singleton;

import java.lang.reflect.Constructor;

public class SingletonDemo3 {

    public static void main(String[] args) throws Exception{
        Singleton instance = Singleton.getInstance();
        Singleton instance1 = Singleton.getInstance();
        System.out.println(instance);
        System.out.println(instance1);
        System.out.println("====================");

        Class<Singleton> clazz = Singleton.class;
        Constructor<Singleton> constructor = clazz.getDeclaredConstructor();
        constructor.setAccessible(true);
        Singleton singleton1 = constructor.newInstance();
        Singleton singleton2 = constructor.newInstance();
        System.out.println(singleton1);
        System.out.println(singleton2);
    }


    private static class Singleton {

        public volatile static Singleton singleton;

        private Singleton () {
            if (singleton != null) {
                throw new RuntimeException("?");
            }
        }

        public static Singleton getInstance() {
           if (singleton == null) {
               synchronized (Singleton.class) {
                   if (singleton == null) {
                       singleton = new Singleton();
                   }
               }
           }
           return singleton;
        }
    }
}
